package recharge

import (
	"context"
	"net/http"
	"strconv"
	"time"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"gitee.com/liuxuezhan/ar-platform/base-common/pkg/xcode"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RechargeOrderListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewRechargeOrderListLogic 用户充值页面--历史记录
func NewRechargeOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeOrderListLogic {
	return &RechargeOrderListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RechargeOrderListLogic) RechargeOrderList(req *types.RechargeListPageRequest) (resp *types.RechargeListPageResponse, err error) {
	uid := uint64(headInfo.GetTokenUid(l.ctx))
	if uid == 0 {
		return nil, xcode.New(http.StatusUnauthorized, "User not login. ")
	}

	var (
		start string
		end   string
	)
	if req.StartTime > 0 {
		start = strconv.FormatInt(req.StartTime, 10)
	}
	if req.EndTime > 0 {
		end = strconv.FormatInt(req.EndTime, 10)
	}

	list, err := l.svcCtx.AssetsRpc.PayRecharge.RechargeTypeList(l.ctx, &rpc.RechargeTypeListRequest{})
	rechargeType := make(map[int64]string, len(list.Records))
	for _, record := range list.Records {
		rechargeType[record.Id] = record.Name
	}

	in := rpc.RechargeListRequest{
		UserId:    uid,
		OrderNo:   "",
		StartTime: start,
		EndTime:   end,
		Status:    uint32(req.Status),
		Type:      req.TypeId,
		Page:      req.Page,
		PageSize:  req.PageSize,
	}
	rechargeResp, err := l.svcCtx.AssetsRpc.PayRecharge.RechargeListPage(l.ctx, &in)
	if err != nil {
		return nil, err
	}
	// 将proto类型转换为API结构体类型
	var records []types.RechargeListPageResponse_Data
	for _, r := range rechargeResp.Records {
		amount, _ := strconv.ParseFloat(r.Amount, 64)
		create, _ := time.Parse("2006-01-02T15:04:05Z", r.CreatedAt)

		records = append(records, types.RechargeListPageResponse_Data{
			Id:        r.Id,
			OrderNo:   r.OrderNo,
			Amount:    amount,
			Status:    r.Status,
			CreatedAt: create.Unix(),
			Type:      rechargeType[int64(r.Type)],
		})
	}
	return &types.RechargeListPageResponse{
		Meta: types.RechargeListPageResponse_Meta{
			PageSize: req.PageSize,
			Page:     req.Page,
			Total:    uint32(rechargeResp.Pagination.Total),
		},
		Data: records,
	}, nil
}
